<?php
/*
 * @Descripttion: 
 * @Author: dedeye
 * @Date: 2020-02-27 12:47:46
 * @LastEditors: dedeye
 * @LastEditTime: 2020-02-29 00:17:31
 */

namespace app\admin\controller;

use app\admin\model\Rule as RuleModel;
use app\common\util\ReturnCode;

class Rule extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if(!request()->isAjax()) {
            return $this->fetch();
        }
        $field = 'id, name, fid, url, target, hash, sort, is_menu, icon, status, create_time';
        $rule = RuleModel::field($field)->append(['status_text'])->all();
        if($rule->isEmpty()) {
            return resultJson(ReturnCode::RESULT_NULL, '暂无数据', []);
        }
        return resultJson(ReturnCode::SUCCESS, 'success', $rule);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        if(!request()->isPost() || !request()->isAjax()){
            return $this->fetch('add');
        }
        $data = input('post.');
        $rule = new RuleModel;
        $addRes = $rule->allowField(true)->save($data);
        if(!$addRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '添加失败');
        }
        return resultJson(ReturnCode::SUCCESS, '添加成功');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $rule = RuleModel::get($id);
        if(is_null($rule)) {
            return resultJson(ReturnCode::RESULT_NULL, '节点不存在');
        }
        return resultJson(ReturnCode::SUCCESS, 'success', $rule);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        if(!request()->isPost() || !request()->isAjax()){
            return $this->fetch('edit');
        }
        $data = input('post.');
        $id = $data['id'];
        unset($data['id']);
        $rule = new RuleModel;
        $addRes = $rule->allowField(true)->save($data, ['id' => $id]);
        if(!$addRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '修改失败');
        }
        return resultJson(ReturnCode::SUCCESS, '修改成功');
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $rule = RuleModel::get($id);
        if(is_null($rule)) {
            return resultJson(ReturnCode::RESULT_NULL, '规则不存在');
        }
        $hasChild = RuleModel::where('fid', $id)->count();
        if($hasChild > 0) {
            return resultJson(ReturnCode::RESULT_FAIL, '该规则存在子规则，无法删除');
        }
        $delRes = $rule->delete();
        if(!$delRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '删除失败');
        }
        return resultJson(ReturnCode::SUCCESS, '删除成功');
    }
}
